package com.itic.mall.mobile.index;



import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.Constants;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.type.UserType;
import com.itic.appbase.framework.utils.IpAddressHelper;
import com.itic.appbase.framework.utils.RandomOrderNumHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.mobile.index.vo.CreateMoneyVo;
import com.itic.mall.mobile.users.livingRate.entity.LivingRateResultVo;
import com.itic.mall.system.finance.makeMoney.persistence.model.MakeMoneyVo;
import com.itic.mall.system.finance.makeMoney.service.FinanceUserMakeMoneyService;
import com.itic.mall.system.msg.apppush.service.AppPushService;
import com.itic.mall.system.msg.type.persistence.model.MsgType;
import com.itic.mall.system.msg.type.service.MsgTypeService;
import com.itic.mall.system.project.controlshow.persistence.model.ProjectControlshowExample;
import com.itic.mall.system.project.livingRate.service.LivingRateService;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;




/**
 * 首页模块接口信息
 * @author 许小宝
 * @time 2017/12/01
 */
@Controller
@RequestMapping(value="/mobile/index")
public class IndexInterface
     extends BaseMobileInterface {

	@Autowired
	private MsgTypeService msgTypeService;

	@Autowired
	private AppPushService appPushService;
	@Autowired
	private FinanceUserMakeMoneyService financeUserMakeMoneyService;
	@Autowired
	private LivingRateService livingRateService;
	
	   /**
	    * APP首页登入
	    * @return
	    */
	   @RequestMapping(value="/index")
	   @ResponseBody
	   public Map<String,Object> index( HttpServletRequest request,HttpServletResponse response,String token,String appId){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   	    Map<String, Object> dataMap = new HashMap<String,Object>();
		   	    //顶部轮播图信息
		   	    dataMap.put("banners", getMarketBannersByType("index"));
		   	   
		   		
		   		//广告位一的信息
			    dataMap.put("advertOnes", getMarketAdvertByTypeAndAddress("index","one"));

			    String isStore = "user";
			    // 惠生钱，用户如果没有登入
			    UsersMall user = getUsersByTokenAndAppId(token, appId);
	   			if( null != user ){
	   				if( "002".equals(user.getType()) ){
		   				isStore = "yun";
		   			}else{
		   				dataMap.put("isLogin", "yes");
		   				Map<String, Object> data =  this.ordersDetailService.getUserTotalCousume(user.getId());
		   				double money = user.getMoney()==null?0:user.getMoney();
		   				LivingRateResultVo livingRateResultVo = this.livingRateService.calUserLivingRate(user);
		   				double totalMoney = this.financeUserMakeMoneyService.getUserTotalMakeMoney(user.getId());
		   				String ratePercent = "30";
		   				double livingMoney = user.getLivingMoney()==null?0:user.getLivingMoney();
		   				String todayMoney = this.livingRateService.calLivingMoney(Double.toString(livingRateResultVo.getYearRate()), Double.toString(livingMoney));
		   				CreateMoneyVo vo = new CreateMoneyVo(); 
		   				vo.setCreateMoney(Double.parseDouble(todayMoney));
		   				vo.setMoney(money);
		   				vo.setTotalComsum((Double)data.get("consume"));
		   				vo.setTotalProfit((Double)totalMoney);
		   				boolean flag = this.livingRateService.compareLivingMoneyWithToday(todayMoney, user.getId());
		   				String upOrDowm = flag?"up":"down";
		   				vo.setUpOrDown(upOrDowm);
		   				vo.setPercent(livingRateResultVo.getYearRate());
		   				dataMap.put("createMoney", vo);
		   			}
	   			}else{
	   				dataMap.put("isLogin", "no");
	   			    //未登录中间广告位图片信息
			   	    dataMap.put("creAdverts", getMarketAdvertByTypeAndAddress("index","creMoney"));
	   			}
		   	    
	   			
	   		     //模块信息
		   		dataMap.put("models", getMarketModelsByType("index",isStore));
		   		
	   			
	   			String isShowCre = "hide";
		   		String isShow = sysSettingService.getByKey("IS_SHOW_CRE_MONEY");
		   		if( "show".equals(isShow) ){
		   			isShowCre = isShow;
		   		}
		   		dataMap.put("isShowCreMoney", isShowCre);
		   		
		   		//友惠家某某到账提醒，用websocket来实现，这是一个h5页面
		   	    StringBuffer clintMsg = new StringBuffer();
		   	    clintMsg.append(IpAddressHelper.getLocalhostName(request));
		   	    clintMsg.append("/mobile/index/initClintMsgs?token=");
		   	    clintMsg.append(token);
		   	    clintMsg.append("&appId=");
		   	    clintMsg.append(appId);
			    dataMap.put("clintMsg",  clintMsg.toString() );
			    
		   		dataMap.put("advertTwos", getMarketAdvertByTypeAndAddress("index","two"));
		   		//爆品专区
		   		dataMap.put("findGoods", getMarketActivitysByType("findgood"));
			    // 广告图二信息
			    dataMap.put("advertThrees", getMarketAdvertByTypeAndAddress("index","three"));
			   	
			    //爆品专区
		   		dataMap.put("ranking", getMarketActivitysByType("ranking"));
		      	//爆品专区
		   		dataMap.put("hoting", getMarketActivitysByType("hoting"));
		   		//获取用户未读消息条数
		   		UsersMall usersMall = this.getUsersByTokenAndAppId(token, appId);
		   		int notReadCount=0;
		   		if(usersMall!=null) {
		   			List<MsgType> msgTypes = this.msgTypeService.getParentMsgType();
		   			for(MsgType msgType :msgTypes) {
		   				notReadCount += this.appPushService.getNotReadCountByTypeId(msgType,usersMall.getId());
		   			}
		   		}
				dataMap.put("notReadCount", notReadCount);
		   		resultMap.put(DATA, dataMap);//封装数据
		   		errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
			   		
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("IndexInterface", "index", e.toString(),"APP首页登入",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	
	  
	   
	   /**
	    * APP首页轮播图信息
	    * @return
	    */
	   @RequestMapping(value="/banners")
	   @ResponseBody
	   public Map<String,Object> banners( HttpServletRequest request,HttpServletResponse response){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   	    //首页轮播图信息
		   		resultMap.put(DATA, getMarketBannersByType("index"));
		   		errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("IndexInterface", "banners", e.toString(),"APP首页轮播图信息",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	  
	   /**
	    * APP首页模块信息
	    * @return
	    */
	   @RequestMapping(value="/models")
	   @ResponseBody
	   public Map<String,Object> models( HttpServletRequest request,HttpServletResponse response, String token ,String appId ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		String isStore = "user";
		   		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) ){
		   			UsersMall user = getUsersByTokenAndAppId(token, appId);
		   			if(null!=user && UserType.ydz.getType().equals(user.getType()) ){
		   				isStore = "yun";
		   			}
		   		}
		   		resultMap.put(DATA, getMarketModelsByType("index",isStore));
		   		errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("IndexInterface", "models", e.toString(),"APP首页模块信息",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	   /**
	    * APP首页广告图一信息
	    * @return
	    */
	   @RequestMapping(value="/advertOnes")
	   @ResponseBody
	   public Map<String,Object> advertOnes( HttpServletRequest request,HttpServletResponse response){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
			try {
				resultMap.put(DATA, getMarketAdvertByTypeAndAddress("index","one"));
				errorCode = SUCCESS_ERROR_CODE;
				errorMsg = SUCCESS_ERROR_MSG;
	
			} catch (Exception e) {
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("IndexInterface", "advertOne", e.toString(),"APP广告图一信息",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	 
	   
	   /**
	    * APP首页惠生钱信息
	    * @return
	    */
	   @RequestMapping(value="/creMoney")
	   @ResponseBody
	   public Map<String,Object> creMoney( HttpServletRequest request,HttpServletResponse response,String token,String appId ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		Map<String,Object> dataMap = new HashMap<String,Object>();
		   	    // 惠生钱，用户如果没有登入
		   		if(StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId)){
		   			UsersMall user = getUsersByTokenAndAppId(token, appId);
		   			if( null != user ){
		   				dataMap.put("isLogin", "yes");
					    CreateMoneyVo vo = new CreateMoneyVo(); 
		   				vo.setCreateMoney(getCreateMoney(user));
		   				vo.setMoney(user.getMoney());
		   				vo.setTotalComsum(user.getTotalComsum());
		   				vo.setTotalProfit(user.getTotalProfit());
		   				vo.setUpOrDown(getUpOrDown(user));
		   				vo.setPercent(13.8);
		   				dataMap.put("account", vo);
		   				resultMap.put(DATA, dataMap);
		   			}
		   		}else{
		   			dataMap.put("isLogin", "no");
	   			    //未登录中间广告位图片信息
			   	    dataMap.put("creAdverts", getMarketAdvertByTypeAndAddress("index","creMoney"));
	   				resultMap.put(DATA, dataMap);
	   			}
		   		errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("IndexInterface", "creMoney", e.toString(),"APP首页惠生钱信息",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	   /**
	    * 获取消息推送链接 的地址
	    * @return
	    */
	   @RequestMapping(value="/clintMsg")
	   @ResponseBody
	   public Map<String, Object> clintMsg( HttpServletRequest request,HttpServletResponse response, Model model,String token,String appId){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		//String yunLevel = user.getYunLevel();
		    	ProjectControlshowExample example = new ProjectControlshowExample();
		   		com.itic.mall.system.project.controlshow.persistence.model.ProjectControlshowExample.Criteria criteria = example.createCriteria();
		   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		   		//criteria.andUserLevelLessThan(yunLevel);//用户等级大于配置表配置等级时展示
		   		criteria.andIsVisibleEqualTo(DBConst.TRUE);
		   		resultMap.put(DATA,IpAddressHelper.getLocalhostName(request)+"/mobile/index/initClintMsgs?token="+token+"&appId="+appId);
		   		errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("IndexInterface", "clintMsg", e.toString(),"APP首页轮播图信息",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	   
	   /**
	    * APPwebsocket消息推送
	    * @return
	    */
	   @RequestMapping(value="/initClintMsgs")
	   public String initClintMsgs( HttpServletRequest request, Model model,String token,String appId){
		   model.addAttribute("wsurl", iticJsonMapper.toJson( IpAddressHelper.getLocalhostWs(request) ) );
		   UsersMall user = getUsersByTokenAndAppId(token, appId);
		   if( null != user ){
			   request.getSession().setAttribute(Constants.WS_USER_ID, user.getId());//如果不是游客就用用户的id
		   }else{
			   request.getSession().setAttribute(Constants.WS_USER_ID, RandomOrderNumHelper.getOrderNumber());//游客都给一个随机的号码吧
		   }
		   return "mall/mobile/index/clintMsgs";
	   }
	   
	   /**
	    * 获取最新的100条生钱数据
	    * @param request
	    * @return
	    */
	   @RequestMapping(value="/getMakeMoneyList")
	   @ResponseBody
	   public Map<String,Object> getMakeMoneyList( HttpServletRequest request,HttpServletResponse response ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		//友惠家某某到账提醒，用websocket来实现，这是一个h5页面
		   		List<MakeMoneyVo> list = financeUserMakeMoneyService.getCreateMoneyList();
		   	    resultMap.put(DATA, list);
		   		errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("IndexInterface", "getMakeMoneyList", e.toString(),"APP生钱数据信息",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	   /**
	    * APP首页动态消息信息（这里引用一个网页，用webSocket来实现）
	    * @return
	    */
	   @RequestMapping(value="/dynaMsg")
	   @ResponseBody
	   public Map<String,Object> dynaMsg( HttpServletRequest request,HttpServletResponse response,String token,String appId){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		//友惠家某某到账提醒，用websocket来实现，这是一个h5页面
		   	    StringBuffer clintMsg = new StringBuffer();
		   	    clintMsg.append(IpAddressHelper.getLocalhostName(request));
		   	    clintMsg.append("/mobile/index/initClintMsgs?token=");
		   	    clintMsg.append(token);
		   	    clintMsg.append("&appId=");
		   	    clintMsg.append(appId);
		   	    resultMap.put(DATA, clintMsg.toString());
		   		errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("IndexInterface", "dynaMsg", e.toString(),"APP首页动态消息",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	   /**
	    * APP首页广告位二信息
	    * @return
	    */
	   @RequestMapping(value="/advertTwo")
	   @ResponseBody
	   public Map<String,Object> advertTwo( HttpServletRequest request,HttpServletResponse response){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
			try {
				resultMap.put(DATA, getMarketAdvertByTypeAndAddress("index","two"));
				errorCode = SUCCESS_ERROR_CODE;
				errorMsg = SUCCESS_ERROR_MSG;
			} catch (Exception e) {
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("IndexInterface", "advertTwo", e.toString(),"APP首页广告位二信息",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	   /**
	    * APP首页发现好货
	    * @return
	    */
	   @RequestMapping(value="/findgood")
	   @ResponseBody
	   public Map<String,Object> findgood( HttpServletRequest request,HttpServletResponse response){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		resultMap.put(DATA, getMarketActivitysByType("findgood"));
				errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("IndexInterface", "findHand", e.toString(),"APP首页发现好货",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	   /**
	    * APP首页广告位三信息
	    * @return
	    */
	   @RequestMapping(value="/advertThree")
	   @ResponseBody
	   public Map<String,Object> advertThree( HttpServletRequest request,HttpServletResponse response){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		    try {
				resultMap.put(DATA, getMarketAdvertByTypeAndAddress("index","three"));
				errorCode = SUCCESS_ERROR_CODE;
				errorMsg = SUCCESS_ERROR_MSG;
		    } catch (Exception e) {
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("IndexInterface", "advertThree", e.toString(),"APP首页广告位三信息",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	   /**
	    * APP首页排行榜信息
	    * @return
	    */
	   @RequestMapping(value="/ranking")
	   @ResponseBody
	   public Map<String,Object> ranking( HttpServletRequest request,HttpServletResponse response){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		resultMap.put(DATA, getMarketActivitysByType("ranking"));
		   		errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("IndexInterface", "ranking", e.toString(),"APP首页排行榜信息",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	   
	   /**
	    * APP首页热门活动信息
	    * @return
	    */
	   @RequestMapping(value="/hoting")
	   @ResponseBody
	   public Map<String,Object> hoting( HttpServletRequest request,HttpServletResponse response){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		resultMap.put(DATA, getMarketActivitysByType("hoting"));
		   		errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("IndexInterface", "hoting", e.toString(),"APP首页热门活动信息",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	   /**
	    * 是否展示惠生钱模块
	    * @return
	    */
	   @RequestMapping(value="/isShowCreMoney")
	   @ResponseBody
	   public Map<String,Object> isShowCreMoney( HttpServletRequest request,HttpServletResponse response){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		String result = "hide";
		   		String isShow = sysSettingService.getByKey("IS_SHOW_CRE_MONEY");
		   		if( "show".equals(isShow) ){
		   			result = isShow;
		   		}
		   		resultMap.put(DATA, result );
		   		errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("IndexInterface", "hoting", e.toString(),"APP首页热门活动信息",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	   
	   
	   
}